package com.wx.rabbitmq.service;

import com.alibaba.fastjson.JSON;
import com.wx.rabbitmq.dao.BrokerMessageLogDao;
import com.wx.rabbitmq.dao.OrderDao;
import com.wx.rabbitmq.entity.BrokerMessageLog;
import com.wx.rabbitmq.entity.Order;
import com.wx.rabbitmq.producer.RabbitOrderSender;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

import static com.wx.rabbitmq.constant.MessageStatus.MESSAGE_STATUS_0;

/**
 * @author wx
 * @Description:
 * @date 2018/12/3 000316:20
 */
@Service
public class OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private BrokerMessageLogDao brokerMessageLogDao;
    @Autowired
    private RabbitOrderSender rabbitOrderSender;

    @Transactional(rollbackFor = RuntimeException.class)
    public void createOrder(Order order) {
        try {
        // 获取当前时间
        Date orderTime = new Date();
        // 新增订单
        orderDao.insert(order);
        // log insert
        BrokerMessageLog brokerMessageLog = new BrokerMessageLog();
        brokerMessageLog.setMessageId(order.getMessageId());
        //save order message as json
        brokerMessageLog.setMessage(JSON.toJSONString(order));
        brokerMessageLog.setStatus(MESSAGE_STATUS_0);
        //设置预计任务完成时间，这里设置的是一分钟后任务会完成
        brokerMessageLog.setNextRetry(DateUtils.addMinutes(orderTime,1));
        brokerMessageLog.setCreateTime(new Date());
        brokerMessageLog.setUpdateTime(new Date());
        brokerMessageLogDao.insert(brokerMessageLog);
        // 发送队列消息
            rabbitOrderSender.sendOrder(order);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("下单失败");
        }

    }
}
